Page({
    data: {
        formData: {
            category: "个人证件",
            subCategory: "身份证",
            name: "",
            phone: "",
            content: "",
            publishDate: "",
            publishDays: 1,
            needInvoice: false,
            invoiceInfo: {
                title: "",
                taxNumber: "",
                email: "",
                receiverPhone: ""
            },
            remark: ""
        },
        price: 0,
        charCount: 0
    },
    
    onLoad() {
        // 初始化发布日期为今天
        const today = this.formatDate(new Date());
        let formData = this.data.formData;
        formData.publishDate = today;
        this.setData({ formData });
    },
    
    // 格式化日期为 YYYYMMDD
    formatDate(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}${month}${day}`;
    },
    
    // 姓名输入事件处理函数
    onNameInput(e) {
        const name = e.detail.value;
        let formData = this.data.formData;
        formData.name = name;
        this.setData({ formData });
    },
    
    // 手机号输入事件处理函数
    onPhoneInput(e) {
        const phone = e.detail.value;
        let formData = this.data.formData;
        formData.phone = phone;
        this.setData({ formData });
    },
    
    // 内容输入事件处理函数
    onContentInput(e) {
        const content = e.detail.value;
        let formData = this.data.formData;
        formData.content = content;
        
        this.setData({ formData });
        this.calculatePrice();
        
        if (content.length < 10) {
            this.setData({
                contentTip: `还需要${10 - content.length}个字符`
            });
        } else {
            this.setData({
                contentTip: ""
            });
        }
    },
    
    // 刊登天数变化事件处理函数
    onDaysChange(e) {
        const days = parseInt(e.detail.value);
        let formData = this.data.formData;
        formData.publishDays = days;
        
        this.setData({ formData });
        this.calculatePrice();
    },
    
    // 发布日期变化事件处理函数
    onDateChange(e) {
        const date = e.detail.value.replace(/-/g, ''); // 将 YYYY-MM-DD 转换为 YYYYMMDD
        let formData = this.data.formData;
        formData.publishDate = date;
        this.setData({ formData });
    },
    
    // 是否需要发票变化事件处理函数
    onNeedInvoiceChange(e) {
        const needInvoice = e.detail.value;
        let formData = this.data.formData;
        formData.needInvoice = needInvoice;
        this.setData({ formData });
    },
    
    // 计算价格
    calculatePrice() {
        const { content, publishDays } = this.data.formData;
        
        // 计算字数（去除空格）
        const charCount = content.replace(/\s/g, '').length;
        
        // 每个字2.5元
        const pricePerChar = 2.5;
        
        // 计算总价：每个字2.5元 × 字数 × 刊登天数
        const price = Math.round(charCount * pricePerChar * publishDays * 100) / 100;
        
        this.setData({
            price: price,
            charCount: charCount
        });
    },
    
    // 表单提交
    submitForm() {
        const formData = this.data.formData;
        
        // 表单验证
        if (!formData.name || formData.name.length < 2) {
            uni.showToast({ title: "姓名必须为2-20个字符", icon: "none" });
            return;
        }
        
        if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
            uni.showToast({ title: "请输入有效的手机号", icon: "none" });
            return;
        }
        
        if (!formData.content || formData.content.length < 10) {
            uni.showToast({ title: "见报内容必须为10-1000个字符", icon: "none" });
            return;
        }
        
        if (!formData.publishDate || !/^\d{8}$/.test(formData.publishDate)) {
            uni.showToast({ title: "请选择有效的刊登日期", icon: "none" });
            return;
        }
        
        if (formData.needInvoice) {
            if (!formData.invoiceInfo.title) {
                uni.showToast({ title: "发票抬头不能为空", icon: "none" });
                return;
            }
            if (!formData.invoiceInfo.taxNumber) {
                uni.showToast({ title: "纳税人识别号不能为空", icon: "none" });
                return;
            }
            if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.invoiceInfo.email)) {
                uni.showToast({ title: "请输入有效的邮箱地址", icon: "none" });
                return;
            }
        }
        
        // 调用云函数提交数据
        uni.showLoading({ title: "提交中..." });
        uniCloud.callFunction({
            name: "addAdRecord",
            data: formData,
            success: (res) => {
                uni.hideLoading();
                if (res.result && res.result.code === 0) {
                    uni.showToast({ title: "提交成功" });
                    // 跳转到支付页面或订单详情页
                    uni.navigateTo({
                        url: `/pages/payment/payment?orderId=${res.result.data.id}&price=${this.data.price}`
                    });
                } else {
                    uni.showToast({ 
                        title: res.result ? res.result.message : "提交失败", 
                        icon: "none" 
                    });
                }
            },
            fail: (err) => {
                uni.hideLoading();
                uni.showToast({ title: "提交失败", icon: "none" });
                console.error(err);
            }
        });
    }
}); 